package com.zoro.dyformservice.support.filter.auth;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class LoginInfoContext {

    private static final String LOGIN_USER_KEY = "login_user";
    private static final ThreadLocal<LoginUser> LOGIN_USER_THREAD_LOCAL = new ThreadLocal<>();

    static void setLoginUser(LoginUser user) {
        LOGIN_USER_THREAD_LOCAL.set(user);
    }

    static LoginUser getLoginUser() {
        return LOGIN_USER_THREAD_LOCAL.get();
    }

    static void clean() {
        LOGIN_USER_THREAD_LOCAL.remove();
    }

    /**
     * 在session 中获取登陆人信息
     *
     * @param session session
     * @return 登陆人信息
     */
    static LoginUser getLoginUser(HttpSession session) {
        if (session == null) {
            return null;
        }
        Object user = session.getAttribute(LOGIN_USER_KEY);
        if (user instanceof LoginUser result) {
            return result;
        } else {
            return null;
        }
    }

    static void setLoginUserToSession(LoginUser user) {
        getSession().setAttribute(LOGIN_USER_KEY, user);
    }

    static HttpSession getSession() {
        return getRequest().getSession();
    }

    static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }
}

